﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySoft.Data;

namespace Caifu.Datas
{
	/// <summary>
	/// 基金分类特性
	/// </summary>
	public class CategoryFeatureData
	{
		/// <summary>
		/// 
		/// </summary>
		public static readonly CategoryFeatureData Instance = new CategoryFeatureData();

		private readonly DbSession dbSession = new DbSession("Caifu");

		/// <summary>
		/// 设置基金分类特性
		/// </summary>
		/// <param name="fundId"></param>
		/// <param name="features"></param>
		public void SetCategoryFeatures(Guid fundId, string[] features)
		{
			if (features != null && features.Length != 0)
			{
				// 转为大写字符;除出重复元素;升序排列
				features = features.Select(p => p.ToUpper()).Distinct().OrderBy(p => p).ToArray();
				// 选取Feature值；升序排列
				var oldFeatures = GetCategoryFeatures(fundId).Select(p => p.Feature).OrderBy(p => p).ToArray();

				// 两者完全相同时则可以跳过设置
				var reset = false;
				if (features.Length == oldFeatures.Length)
				{
					for (int i = 0; i < features.Length; i++)
					{
						if (features[i] != oldFeatures[i])
						{
							reset = true; //直到有不同时需要重新设置
						}
					}
				}
				if (!reset) return;
			}

			// 开始事务
			using (var transaction = dbSession.BeginTrans())
			{
				try
				{
					var where = CategoryFeature._.FundId == fundId;
					// 先删除
					transaction.Delete<CategoryFeature>(where);
					// 再添加
					foreach (var feature in features)
					{
						CategoryFeature categoryFeature = new CategoryFeature();
						categoryFeature.FundId = fundId;
						categoryFeature.Feature = feature;
						AddPrepare(categoryFeature);
						transaction.Save(categoryFeature);
					}
					// 提交事务
					transaction.Commit();
				}
				catch
				{
					// 回滚事务
					transaction.Rollback();
					throw;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fundId"></param>
		/// <returns></returns>
		public IList<CategoryFeature> GetCategoryFeatures(Guid fundId)
		{
			var where = CategoryFeature._.FundId == fundId;
			return dbSession.From<CategoryFeature>()
				.Where(where)
				.ToList();
		}

		/// <summary>
		/// 加入前的准备
		/// </summary>
		/// <param name="feature"></param>
		void AddPrepare(CategoryFeature feature)
		{
			if (feature.Id == Guid.Empty) feature.Id = Itfort.Comb.NewComb();
			if (feature.AddTime == DateTime.MinValue) feature.AddTime = DateTime.Now;
			if (feature.UpdateTime == DateTime.MinValue) feature.UpdateTime = DateTime.Now;
			feature.Feature = feature.Feature.ToUpper();
		}
	}
}
